package com.ruoyi.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.YnStatusEnum;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.pdf.FileUtil;
import com.ruoyi.common.utils.pdf.WordUtil;
import com.ruoyi.system.entity.AppJobExplanPdfPath;
import com.ruoyi.system.entity.PreventionRiskOught;
import com.ruoyi.system.mapper.PreventionRiskOughtMapper;
import com.ruoyi.system.service.AppJobExplanPdfPathService;
import com.ruoyi.system.service.PreventionRiskOughtService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 风险应知卡 服务实现类
 * </p>
 *
 * @author liushuai
 * @since 2023-03-10
 */
@Slf4j
@Service("preventionRiskOughtService")
public class PreventionRiskOughtServiceImpl implements PreventionRiskOughtService {

    @Resource
    private AppJobExplanPdfPathService appJobExplanPdfPathService;
    @Resource
    private PreventionRiskOughtMapper preventionRiskOughtMapper;

    @Override
    public List<PreventionRiskOught> queryByPage(PreventionRiskOught preventionRiskOught) {
        preventionRiskOught.setYn(YnStatusEnum.Y.getCode());
        return preventionRiskOughtMapper.queryAllByLimit(preventionRiskOught);
    }

    @Override
    public PreventionRiskOught queryById(Integer id) {
        return this.preventionRiskOughtMapper.queryById(id);
    }

    @Override
    public PreventionRiskOught insert(PreventionRiskOught preventionRiskOught) {
        preventionRiskOught.setYn(YnStatusEnum.Y.getCode());
        preventionRiskOught.setCreateUser(SecurityUtils.getUsername());
        this.preventionRiskOughtMapper.insert(preventionRiskOught);
        return preventionRiskOught;
    }

    @Override
    public PreventionRiskOught update(PreventionRiskOught preventionRiskOught) {
        this.preventionRiskOughtMapper.update(preventionRiskOught);
        return this.queryById(preventionRiskOught.getId());
    }

    @Override
    public boolean deleteById(Integer id) {
        return this.preventionRiskOughtMapper.deleteById(id) > 0;
    }

    @Override
    public AjaxResult fillPDFData(Integer id, HttpServletRequest request, HttpServletResponse response) {

        HashMap<String, Object> objectHashMap = new HashMap<>();

        //根据id查询数据
        PreventionRiskOught preventionRiskOught = preventionRiskOughtMapper.queryById(id);
        if (null == preventionRiskOught) {
            return AjaxResult.error("根据id未查询到数据 id:{}", id);
        }

        objectHashMap.put("riskNumber", preventionRiskOught.getRiskNumber());
        objectHashMap.put("riskJobName", preventionRiskOught.getRiskJobName());
        objectHashMap.put("riskGrade", preventionRiskOught.getRiskGrade());
        objectHashMap.put("riskAccidentRisk", preventionRiskOught.getRiskAccidentRisk());
        objectHashMap.put("responsibleDepartment", preventionRiskOught.getResponsibleDepartment());
        objectHashMap.put("personResponsible", preventionRiskOught.getPersonResponsible());
        objectHashMap.put("riskPrimaryHazard", preventionRiskOught.getRiskPrimaryHazard());
        objectHashMap.put("riskControl", preventionRiskOught.getRiskControl());
        objectHashMap.put("riskEmergencyDisposal", preventionRiskOught.getRiskEmergencyDisposal());

        List<String> nameList = new ArrayList<>();
        if (StringUtils.isNotEmpty(preventionRiskOught.getRiskSafetyWarning())) {
            String riskOughtRiskSafetyWarning = preventionRiskOught.getRiskSafetyWarning();
            if (riskOughtRiskSafetyWarning.contains(",")) {
                String[] split = riskOughtRiskSafetyWarning.split(",");
                nameList.addAll(Arrays.asList(split));
            } else {
                nameList.add(riskOughtRiskSafetyWarning);
            }
        }

        if (!CollectionUtils.isEmpty(nameList)) {
            int i = 1;
            for (String name : nameList) {
                PreventionRiskOught preventionRiskOughtRequest = new PreventionRiskOught();
                preventionRiskOughtRequest.setRiskSafetyWarning(name);
                preventionRiskOughtRequest.setYn(YnStatusEnum.N.getCode());
                List<PreventionRiskOught> preventionRiskOughts = preventionRiskOughtMapper.queryAllByLimit(preventionRiskOughtRequest);
                if (!CollectionUtils.isEmpty(preventionRiskOughts)) {
                    preventionRiskOught = preventionRiskOughts.stream().findFirst().orElse(new PreventionRiskOught());
                    if (StringUtils.isNotEmpty(preventionRiskOught.getFileUrl())) {
                        objectHashMap.put("anfileUrl" + i, preventionRiskOught.getFileUrl());
                        i++;
                    }
                }
            }
        }

        log.info("根据id未查询到数据 结果:{}", JSON.toJSONString(preventionRiskOught));

        //查询安全承诺卡路径
        AppJobExplanPdfPath appJobExplanPdfPath = appJobExplanPdfPathService.queryById(999);
        log.info("风险应知卡 结果:{}", JSON.toJSONString(appJobExplanPdfPath));

        if (null == appJobExplanPdfPath) {
            return AjaxResult.error("风险应知卡 999");
        }

        String templateDir = appJobExplanPdfPath.getValueBase();
        try {
            String pdfFilePath = WordUtil.word2pdf(templateDir, appJobExplanPdfPath.getName(), id + "", objectHashMap, new ArrayList<>());
            if (StringUtils.isBlank(pdfFilePath)) {
                return AjaxResult.error("参数转换异常");
            }
            downFile(request, response, FileUtil.getFileNameSuffix(pdfFilePath), pdfFilePath);
        } catch (Exception e) {
            log.error("异常信息", e.fillInStackTrace());
            return AjaxResult.error("参数转换异常");
        } finally {
            //删除文件
            String zyExportPath = FileUtil.getZyExportDir(WordUtil.EXPORT_DIR, id + "");
            FileUtil.delFileByPath(zyExportPath);
        }

        return AjaxResult.success();
    }

    /**
     * 下载文件到浏览器
     *
     * @param request
     * @param response
     * @param filename 要下载的文件名
     * @param filePath 需要下载的文件对象
     * @throws IOException
     */
    private void downFile(HttpServletRequest request, HttpServletResponse response, String filename, String filePath) throws IOException, URISyntaxException {
        //log.info("fileName:{}", filename);
        File file = new File(filePath);

        //  文件存在才下载
        if (file.exists()) {
            OutputStream out = null;
            FileInputStream in = null;
            try {
                // 1.读取要下载的内容
                in = new FileInputStream(file);

                // 2. 告诉浏览器下载的方式以及一些设置
                // 解决文件名乱码问题，获取浏览器类型，转换对应文件名编码格式，IE要求文件名必须是utf-8, firefo要求是iso-8859-1编码
                String agent = request.getHeader("user-agent");
                if (agent.contains("FireFox")) {
                    filename = new String(filename.getBytes("UTF-8"), "iso-8859-1");
                } else {
                    filename = URLEncoder.encode(filename, "UTF-8");
                }
                // 设置下载文件的mineType，告诉浏览器下载文件类型
                String mineType = request.getServletContext().getMimeType(filename);
                response.setContentType(mineType);
                // 设置一个响应头，无论是否被浏览器解析，都下载
                response.setHeader("Content-disposition", "attachment; filename=" + filename);
                // 将要下载的文件内容通过输出流写到浏览器
                out = response.getOutputStream();
                int len = 0;
                byte[] buffer = new byte[1024];
                while ((len = in.read(buffer)) > 0) {
                    out.write(buffer, 0, len);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                WordUtil.close(in);
                WordUtil.close(out);
            }
        }
    }

}
